<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\ProductBatch\Circulation;
use App\Admin\Actions\ProductBatch\MarketSale;
use App\Admin\Actions\QRcode\SaleCode;
use App\Models\ProductsBatchModel;
use App\Models\ProductsSaleModel;
use Encore\Admin\Admin;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class SaleHistoryController extends AdminController
{
    use HasResourceActions;

    protected $title = '销售记录';

    public function index(Content $content)
    {
        return $content
            ->header(trans('admin.sale_history'))
            ->description(trans('admin.list'))
            ->body($this->grid()->render());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new ProductsSaleModel());

        $grid->model()->orderBy('sale_id', 'desc');
        $grid->model()->link = "http://trace.test.com//media/uploads/%E7%BE%8E%E5%9B%BE%E6%8E%A7%E6%8E%A7kong-25.jpg";
        $grid->column('customer.name', '客户');
        $grid->column('productBatch.product.product_name', '商品');
        $grid->column('productBatch.source_code', '商品溯源码')->copyable();
        $grid->column('code', '入市溯源码')->copyable();

        /**
         * 二维码(原本是要写在bootstarp里的,但只有在display方法里可以获取到行数据,所以无奈写在这里了)
         */
        $script = <<<'SCRIPT'
$('.grid-column-qr_code').popover({
    html: true,
    container: 'body',
    trigger: 'focus'
});
SCRIPT;
        Admin::script($script);
        $grid->column('二维码')->display(function ($code) {
            $code = $this->code;
            if ($this->sale_type == '流通') {//流通
                $code = $this['ProductBatch']['source_code'];
            }
            $url = route('admin.scan.result', ['source_code' => $code]);
            $img     = base64_encode(QrCode::format('png')->size(150)->generate($url));
            $img_tag = '<img src="data:image/png;base64,%s">';
            $img     = sprintf(
                $img_tag,
                $img
            );
            return <<<HTML
<a href="javascript:void(0);" class="grid-column-qr_code text-muted" data-content='{$img}' data-toggle='popover' tabindex='0'>
    <i class="fa fa-qrcode"></i>
</a>&nbsp;二维码
HTML;
        });

        $grid->column('sale_num_unit', '销售数量')->display(function () {
            return $this['sale_num'] . ProductsBatchModel::MAP_UNIT[$this->toArray()['product_batch']['unit']];
        });
        $grid->disableActions();
//        $grid->actions(function ($action) {
//            $action->disableView();
//            $action->disableDelete();
//            $action->disableEdit();
////            $action->add(new SaleCode());
//        });

        $grid->disableCreateButton();
        return $grid;
    }
}
